package com.doudou.oauth.controller;

import com.doudou.commons.entity.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.web.savedrequest.DefaultSavedRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.security.Principal;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Controller
public class HomeController {

    @RequestMapping("/")
    @ResponseBody
    public String home(Principal user){
        return String.format("已登录:%s",user.getName());
    }

    @RequestMapping(value = "/login",method = RequestMethod.GET)
    public String login(String error, HttpServletRequest request){
        return "redirect:/index.html#/";
    }

    @RequestMapping(value = "/successPage")
    @ResponseBody
    public Result successPage(HttpServletRequest request){
        log.info("------------------------------登录成功--------------------");
        Map<String, Object> params = new HashMap<>();
        DefaultSavedRequest savedRequest = (DefaultSavedRequest) request.getSession().getAttribute("SPRING_SECURITY_SAVED_REQUEST");

        String returnURL="default";
        if(savedRequest!=null && savedRequest.getRedirectUrl()!= null){
            returnURL  = savedRequest.getRedirectUrl();
        }
        params.put("url",returnURL);


        params.put("token","");

        return Result.ok(params);
    }

    @RequestMapping(value = "/failurePage")
    @ResponseBody
    public Result failurePage(HttpServletRequest request){
        log.info("------------------------------登录失败--------------------");
        return Result.fail("用户名或者密码错误");
    }
}
